package cn.leaf.uc.service.controller;

import cn.leaf.common.api.Result;
import lombok.AllArgsConstructor;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * description: 认证登陆
 *
 * @author twinkle leaf
 * @version v1.0.0
 * @since 2021-11-08 17:10:12
 * slogan: There are no two identical leaves in the world.
 *
 */
@RestController
@RequestMapping("/oauth")
@AllArgsConstructor
public class OauthController {

	private final TokenEndpoint tokenEndpoint;

	@GetMapping("/token")
	public Result<?> getAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
		return custom(tokenEndpoint.getAccessToken(principal, parameters).getBody());
	}

	@PostMapping("/token")
	public Result<?> postAccessToken(Principal principal, @RequestBody Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
		return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
	}

	/**
	 * 自定义返回格式
	 *
	 * @param accessToken 　Token
	 * @return Result
	 */
	private Result<?> custom(OAuth2AccessToken accessToken) {
		DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
		Map<String, Object> data = new LinkedHashMap<>(token.getAdditionalInformation());
		data.put("expiresIn", token.getExpiresIn());
		data.put("accessToken", token.getValue());
		if (token.getRefreshToken() != null) {
			data.put("refreshToken", token.getRefreshToken().getValue());
		}
		return Result.data(data);
	}
}
